package com.typhoon.spring_shiro.controller.kaptcha;

import java.io.IOException;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;

import com.typhoon.spring_shiro.controller.BaseController;
import com.typhoon.spring_shiro.utils.CaptchaUtil;

/**
 * 验证码通用操作类
 * 
 * @author Typhoon
 * @date 2017-05-23 19:32
 * @since V2.0
 */
public abstract class AbstractCaptchaController extends BaseController {

	@Resource(name = "captchaUtil")
	private CaptchaUtil captchaUtil;

	/**
	 * 获取验证码
	 *
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	public void getCaptcha(HttpServletRequest request, HttpServletResponse response) throws IOException {
		captchaUtil.getCaptcha(request, response);
	}

	/**
	 * 获取生成的验证码字符
	 *
	 * @param request
	 * @return
	 */
	public String getGeneratedCode(HttpServletRequest request) {
		return CaptchaUtil.getGeneratedCode(request);
	}
	
	/**
	 * 校验用户验证码是否通过
	 * 
	 * @param userCode
	 * @param request
	 * @param response
	 * @return
	 */
	protected boolean validateUserCode(String userCode,HttpServletRequest request, HttpServletResponse response) {
		if(StringUtils.isEmpty(userCode)) {
			this.putFailtResult(response,"用户验证码为空");
			return false;
		}
		String serverCode = getGeneratedCode(request); // 获取已生成的验证码
		if (StringUtils.isEmpty(serverCode)) {
			this.putFailtResult(response, "服务端验证码为空");
			return false;
		}
		if (!userCode.equalsIgnoreCase(serverCode)) {
			this.putFailtResult(response, "验证码错误");
			return false;
		}
		return true;
	}
}
